from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib import auth 
from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
from ticketer.models import *

@csrf_protect
def login(request):
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username=username, password=password)
    else:
        user = None
    if user is not None:
       if user.is_active:
           auth.login(request, user)
           return render_to_response('ticketer/index.html', { 'user': user, 'failure': False}, context_instance=RequestContext(request))
       else:
           return render_to_response('ticketer/login.html', { 'failure': True }, context_instance=RequestContext(request))
    else:
       return render_to_response('ticketer/login.html', {'failure': True}, context_instance=RequestContext(request))


def logout(request):
    auth.logout(request)
    return render_to_response('ticketer/login.html', {'logout': True })

def index(request):
    tickets = Ticket.objects.exclude(status='C').exclude(status='S')
    user = request.user
    return render_to_response('ticketer/index.html', {'user': user, 'tickets': tickets})


